var app = angular.module("listApp", []),
	parid = UI.getParameterByName('parId');
var timeout_json = function(data, $window) {
	if(data.returnCode == 999994) {
		var ss = 3;
		layer.msg(data.returnMessage + "！<strong class='Ajax_Out'>" + ss + "</strong> 秒后前往登录页", 50, -1);
		var picInt = setInterval(function() {
			if(ss >= 1) {
				ss = ss - 1;
				$('.Ajax_Out').text(ss);
			} else {
				clearInterval(picInt);
				try {
					$window.parent.location.href = data.returnData;
					$window.location.href = data.returnData;
				} catch(e) {
					log('timeout!')
				}
			}
		}, 1000);
		return false;
	}
}

app.config(function($httpProvider) {
	$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
});
app.config(['$compileProvider', function ($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|javascript|mailto|tel|file|sms):/);
     // Angular v1.2 之前使用 $compileProvider.urlSanitizationWhitelist(...)
}]);

app.controller('tableCtrl', function($scope, $http, $window) {
	var vm = $scope.vm = {
		pageIndex: 1,
		pageSize: 10,
		name:'',
		groupId:'',
		userId:'',
		cycleId: '',
		startTime: '',
		endTime: ''
	}
	var stpage = function(ii) {
		var jpage = [],
			index = vm.pageIndex,
			pcount = vm.pageSize,
			total = $scope.datasPage.totalRecords;
		len = 0,
			j = 0,
			pindex,
			tii = (ii - 1) / 2,
			sii = (ii - 1);
		if(total % pcount == 0) {
			len = total / pcount;
		} else {
			len = parseInt(total / pcount) + 1;
		}
		if(len >= ii) {
			if(index < ii) {
				for(var i = 1; i <= len; i++) {
					j++;
					if(j <= ii) jpage.push(i);
				}
			} else if(index >= len - sii) {
				var pindex = index < len - tii ? index - tii : len - sii;
				for(var i = pindex; i <= len; i++) {
					j++;
					if(j <= ii) jpage.push(i);
				}
			} else {
				for(var i = index - tii; i <= len; i++) {
					j++;
					if(j <= ii) jpage.push(i);
				}
			}
		} else {
			for(var i = 1; i <= len; i++) {
				jpage.push(i);
			}
		};
		$scope.pages_e = len;
		$scope.pages = jpage;
	}
	
	//删除
	$scope.domAjax = function(e, id,name,groupName) {
		var ids = '',
			de_id=id;
		$('.td .ui_checkbox.checked').each(function() {
			ids = ids + $(this).attr('data-id') + ',';
		});
//		if(ids.length>0){ 
//			//删除多条
//			ids = ids.substr(0, ids.length - 1);
//			id=ids;
//			$('.layerInfoArea .jtit p').eq(0).text('是否删本条内容！');
//		}
		if((e === 'del') || (e === 'delAll')) {
			$.layer({
				title: "温馨提示：",
				shade: [0],
				area: ['230', 'auto'],
				dialog: {
					msg: '确定删除吗？',
					btns: 2,
					type: -1,
					btn: ['确定', '取消'],
					yes: function() {
						//删除
						$http.get(basePath + '/rpt/display/delete.do?groupName='+groupName+'&name='+name+'&id=' + id).success(function(data) {
							var j = timeout_json(data, $window);
							if(j == false) {
								return false;
							}
							layer.msg(data.returnMessage, 1, -1);
							setTimeout(function() {
								if(window.reLength==1&&vm['pageIndex']>1){
									$scope.setAjax({
										"pageindex" : vm['pageIndex']-1,
										"startTime": $('#start_t').val(),
										"endTime": $('#end_t').val()
									});
								}else{
									$scope.setAjax();
								}
							},1000);
						});

					},
					no: function() {}
				}
			});
		} 
	}

    $scope.modifyBtn = function(id) {
    	if(id != undefined) {
    		$http.get(basePath + 'report/queryByID.do?ifm_id=' + id).success(function(data) {
    			var j = timeout_json(data, $window);
    			if(j == false) {
    				return false;
    			}
    			if(data.returnCode == 10000) {
    				content = $scope.content = data.returnData;
    		        $.layer({
    		            title: "温馨提示：",
    		            shade: [0],
    		            area: ['230', 'auto'],
    		            dialog: {
    		                msg: '确定要修改为'+($scope.content.ifm_isdelete==0?"开启状态?":"关闭状态"),
    		                btns: 2,
    		                type: -1,
    		                btn: ['确定', '取消'],
    		                yes: function() {
    		        			var params = {
    		    					report_id: content.report_id,
    		    					report_name: content.report_name,
    		    					report_type: content.report_type,
    		    					report_note: content.report_note,
    		    					report_isdelete: content.report_isdelete
    		    				};
    		        			//0--表示目前为关闭状态，点击按钮后请求开启，所以赋值为1，再发送。
    		        			if(params.report_isdelete==0){
    		        				params.report_isdelete=1;
    		        			}else{
    		        				params.report_isdelete=0;
    		        			}
    		                    $.post(basePath + 'iformation/modifyIformation.do', params).success(function(data) {
    		                        var j = timeout_json(data, $window);
    		                        if(j == false) {
    		                            return false;
    		                        }
    		            			layer.msg(data.returnMessage, 1, 10);
    		                        setTimeout(function() {
    		                            $scope.setAjax();
    		                        },800);
    		                    });
    		                },
    		                no: function() {}
    		            }
    		        });
    			}
    		});
    	} 
    }
	
	$scope.setAjax = function(obj) {
		if(obj) {
			vm["pageSize"] = obj.pagesize || vm["pageSize"];
			vm["pageIndex"] = obj.pageindex || vm["pageIndex"];
			//判断输入的页数是否大于最大的页数
			if(vm["pageIndex"]>$scope.pages_e && $scope.pages_e!=0){
				vm["pageIndex"]=$scope.pages_e;
			}
			vm["startTime"]= obj.startTime;
			vm["endTime"] = obj.endTime;
			if((vm["startTime"]==""&&vm["endTime"]!="")||(vm["startTime"]!=""&&vm["endTime"]=="")){
				layer.msg("时间范围不完整，请重新选择生成时间！",2,8);
				return false;
			}else if(vm["startTime"]>vm["endTime"]){
				layer.msg("开始时间不能大于结束时间！",2,8);
				return false;
			}
		}
		$scope.addparid = parid;
		vm.cycleId = $("#reportSelects").val();
		url = basePath + 'rpt/display/selectRptInfo.do?pageIndex=' + vm['pageIndex'] + '&pageSize=' + vm['pageSize'] + '&vtimes=' + new Date().getTime();
		if(vm.name != undefined && vm.name != "") url = url + '&name=' + encodeURIComponent(vm['name']);
		if(vm.groupId != undefined && vm.groupId != "") url = url + '&groupId=' + vm['groupId'];
		if(vm.userId != undefined && vm.userId != "") url = url + '&userId=' + vm['userId'];
		if(vm.cycleId != undefined && vm.cycleId != "") url = url + "&cycleId=" + vm['cycleId'];
		if(vm.startTime!=undefined && vm.startTime!="") url = url + '&releaseTime1='+ vm['startTime'];
		if(vm.endTime!=undefined && vm.endTime!="") url = url + '&releaseTime2='+ vm['endTime'];
	    var dLoading='';
	    $scope.dLoading=true;
	    $(".fuzzy").addClass("fuzzyCss");
	    
		$http.get(url).success(function(data) {
			//获取本次返回数据的条数
			window.reLength = data.returnData.length;
			//取得当前页面的上一页、下一页
			$scope.prevIndex = parseInt($("#jsgo .cur").text())-1;
			$scope.nextIndex = parseInt($("#jsgo .cur").text())+1;
			
			var j = timeout_json(data, $window);
			if(j == false) {
				return false;
			}
			$('#zcont').removeClass('checked');
			var datasR = data.returnData;
			
			for(var i =0;i<datasR.length;i++){
				var usersLen = datasR[i].users.length;
				var usersArr = [];
				for(var j=0;j<usersLen;j++){
					usersArr.push(datasR[i].users[j].userName);
				}
				var usersStr = usersArr.join(',');
				datasR[i].users = usersStr;
			}
			//以下代码后来变更
/*			for(var i =0;i<datasR.length;i++){
				if(datasR[i].userIDName){
					var userNames = datasR[i].userIDName.split('|')[1];
				}else{
					var userNames = "";
				}
				datasR[i].users = userNames;
			}*/
			
			$scope.datas = datasR;
			$scope.datasPage = data;
			stpage(7);
			$scope.dLoading=false;
			 $(".fuzzy").removeClass("fuzzyCss");
			 
			if(window.reLength==1){
				$scope.selectH = true;
			}else{
				$scope.selectH = false;
			}
			 
			if($scope.dLoading==false){
				if(data.returnData.length <= 0) {
					layer.msg('无数据！', 1, -1);
				}
			}
			$scope.keyInt="";
		});
	};
	$scope.setAjax();
	
	$scope.goAjax = function() {
		$scope.setAjax({
			"pageindex" : $scope.keyInt,
			"startTime" : $('#start_t').val(),
			"endTime" : $('#end_t').val()
		});
	}

	$scope.getAjax = function() {
		vm["pageIndex"] = 1;
		$scope.setAjax({
			"startTime":$('#start_t').val(),
			"endTime":$('#end_t').val()
		});
	}

	$(document).live('keyup', function(e) {
		e = e || window.event;
		if(e.keyCode == 13) {
			$scope.getAjax();
		}
	});
	
	$scope.start = {
		elem: '#start_t',
		format: 'YYYY-MM-DD hh:mm:ss',
		max: laydate.now(),
		choose:function(datas){
			$scope.end.min = datas;//开始日选好后，重置结束日的最小日期
		}
	};
	$scope.end = {
		elem: '#end_t',
		format: 'YYYY-MM-DD hh:mm:ss',
		max: laydate.now(),
		choose: function(datas){
			$scope.start.max = datas;//结束日选好后，重置开始日的最大日期
		}
	};
	laydate($scope.start);
	laydate($scope.end);
});

app.directive('pagen', function() { //页总数
	return {
		link: function($scope, ele) {
			ele.bind('click', function() {
				var pagesize = $(this).text();
				$(ele).addClass('cur').siblings().removeClass('cur');
				$scope.setAjax({
					"pagesize": pagesize,
					"pageindex": 1,
					"startTime": $('#start_t').val(),
					"endTime": $('#end_t').val()
				});
			});
		}
	}
});
app.directive('pageg', function() { //fenye
	return {
		link: function($scope, ele) {
			ele.bind('click', function() {
				var index = $(this).attr('data-href');
				/**
				 * 条件一：如果index为非数字，点击上一页，设为当前页码-1;
				 * 条件二：如果index为非数字，点击下一页，设为当前页码+1;
				 */
				if(isNaN(index) && $(this).attr('class')=="str"){
					index = parseInt($("#jsgo .cur").text())-1;
				}else if(isNaN(index) && $(this).attr('class')=="end"){
					index = parseInt($("#jsgo .cur").text())+1;
				}
				$scope.setAjax({
					"pageindex": index,
					"startTime":$('#start_t').val(),
					"endTime":$('#end_t').val()
				});
			});
		}
	}
});

app.directive('agSelectc',function($http){ 
	return { 
		restrict:'AE',
		scope:{ 
			groupId:'=groupId'
		},
		template:'<div class="ui_select"><input type="text" id="groupInputText" class="ui_s_t" ng-bind="stxt" ng-model="stxt" /><div class="ui_s_bk"><a href="javascript:void(0)" class="cur" data-id="">全部</a><a href="javascript:void(0)" ng-repeat="key in dataGroupSelects | filter: {groupName:stxt} " ng-bind="key.groupName" data-id="{{key.groupId}}"></a></div></div>',
		controller:function($scope,$element,$attrs){ 
			var a = $element.find('.ui_s_t'),
				b = $element.find('.ui_s_bk'),
				c = $attrs.ajaxs,
				d = $attrs.loadajaxs;
			$element.children('.ui_select').css('zIndex',101);
			$element.bind('click', function() {
				b.slideDown(100, "easeInSine");
			});
			$element.bind('mouseleave', function() {
				if(a.text()!=""){
					b.hide();
				}
			});
		},
		link:function($scope,$element,$attrs){ 
			$scope.stxt='全部';
			var a=$element.find('.ui_s_t'),
				b=$element.find('.ui_s_bk'),
				c=$attrs.ajaxs;
			if(c!=undefined){
				$http.get(c+'?vtimes='+new Date().getTime()).success(function(data){ 
					$scope.dataGroupSelects=data.returnData;
				});
			}			
			a.click(function() {
				$scope.stxt=undefined;
				$scope.$apply();
			});
			b.find('a').live("click",function(){ 
				$("#defaultId").trigger('click');
				b.hide();
				$(this).addClass('cur').siblings().removeClass('cur');
				a.val($(this).text());
				$scope.stxt=$(this).text();
				if($attrs.groupId!=undefined) {
					$scope.groupId=$(this).attr('data-id'); 
					$("#groupIds").val($(this).attr('data-id'));
				}
				$scope.$apply();
				$("#defaultId").parent().css("display","none");
 				return false;
			});
			$element.bind('mouseleave',function(){ 
				$("#groupInputText").val(b.find('a.cur').text());
				b.find('.ui_s_t').blur();
				b.hide();
//				$scope.$apply();
				return false;
			});
		}
	}
});

app.directive('agSelectd',function($http){ 
	return { 
		restrict:'AE',
		scope:{ 
			userId:'=userId'
		},
		template:'<div class="ui_select"><input type="text" id="userInputText" class="ui_s_t" ng-bind="stxt" ng-model="stxt" /><div class="ui_s_bk"><a href="javascript:void(0)" id="defaultId" class="cur" data-id="">全部</a><a href="javascript:void(0)" ng-repeat="key in dataUserNameSelects | filter: {userName:stxt} " ng-bind="key.userName" data-id="{{key.userId}}"></a></div></div>',
		controller:function($scope,$element,$attrs){ 
			var a = $element.find('.ui_s_t'),
				b = $element.find('.ui_s_bk'),
				c = $attrs.ajaxs,
				d = $attrs.loadajaxs;
			$element.children('.ui_select').css('zIndex',99);
			$element.bind('click', function() {
				if (c != undefined) {
					var groupId=$('#groupIds').val() ||0;
					$http.get(c+ '?groupId=' + groupId + '&vtimes=' + new Date().getTime()).success(function(data) {
						$scope.dataUserNameSelects = data.returnData;
					});
				}
				b.slideDown(100, "easeInSine");
			});
			$element.bind('mouseleave', function() {
				if(a.text()!=""){
					b.hide();
				}
			});
		},
		link:function($scope,$element,$attrs){ 
			$scope.stxt='全部';
			var a=$element.find('.ui_s_t'),
				b=$element.find('.ui_s_bk'),
				c=$attrs.ajaxs;
		
			a.click(function() {
					$scope.stxt=undefined;
					$scope.$apply();
			});
			b.find('a').live("click",function(){ 
				b.hide();
				a.val($(this).text());
				$scope.stxt=$(this).text();
				if($attrs.userId!=undefined) {
					$scope.userId=$(this).attr('data-id');
					$("#userIds").val($(this).attr('data-id'));
				}
				$scope.$apply();
 				return false;
			});
			$element.bind('mouseleave',function(){ 
				if ((b.find('a').eq(0).text() != '全部') || (!$scope.stxt)) {
					if (b.find('a.cur').length) {
						b.find('a.cur').trigger('click');
					} 
				} 
				b.find('.ui_s_t').blur();
				b.hide();
				return false;
			});
		}
	}
});

$(function() {
	laydate.skin('molv');
	$('.ui_select_msg').each(function() {
		var _ = $(this),
			_a = _.find('.ui_s_t_msg'),
			_c = _.find('.ui_s_bk_msg'),
			_ca = _c.find('a');
		_a.live('click', function() {
			_c.slideToggle(200, "easeInSine");
		});
		_ca.live('click', function() {
			$(this).addClass('cur').siblings().removeClass('cur');
			_a.text($(this).text());
			$("#reportSelects").val($(this).attr("type"));
			_c.slideToggle(200, "easeInSine");
		});
		_c.live('mouseleave', function() {
			_c.stop(false, true).slideUp(200, "easeInSine");
		});
	});

	$('.ui_select_msg').live('keyup', function(e) {
		var _ = $(this),
			b = _.find('.ui_s_bk_msg'),
			di = 27;
		_.focus();
		e = e || window.event;
		var indx = b.find('a.cur').index() || 0;
		if(e.keyCode == 40) {
			var aindx = indx + 1,
				sct;
			if(rindx >= b.find('a').length) {
				rindx = b.find('a').length;
			}
			b.find('a').eq(aindx).addClass('cur').siblings('a').removeClass('cur');
			sct = aindx * di > 180 ? aindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 38) {
			var rindx = indx - 1,
				sct;
			sct = aindx * di > 100 ? aindx * di : 0;
			if(rindx <= 0) {
				rindx = 0;
			}
			b.find('a').eq(rindx).addClass('cur').siblings('a').removeClass('cur');
			sct = rindx * di > 180 ? rindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 13) {
			b.find('a.cur').trigger('click');
			_.blur();
			_.find('.ui_s_t_msg').blur();
		}
		return false;
	});
	
	$('#zcont').on('click', function() {
		$(this).toggleClass('checked');
		if ($(this).attr('class').search('checked') > -1) {
			$('.td .ui_checkbox').addClass('checked');
		} else {
			$('.td .ui_checkbox').removeClass('checked');
		}
	});
	$('.td .ui_checkbox').live('click', function() {
		$(this).toggleClass('checked');
	});
	
	var editExaDataLayer = null;
	$('.editExaDataBtn').live('click', function() {
		var editExaDataLayer = $.layer({
			type: 1,
			title: false,
			area: ['500', '300'],
			border: [0], //去掉默认边框
			shade: [0.3, '#000'], //去掉遮罩
			closeBtn: [0, false], //去掉默认关闭按钮
			fadeIn: 500,
			move: "#editExaData_tile",
			page: {
				dom: '#editExaDataLayer'
			}
		});
		//自设关闭
		$('#editExaDataLayer > .closeBtn,#editExaDataLayer .cancelLayer').live('click', function() {
			layer.close(editExaDataLayer);
		});
	});

	$("#editExaSubmitBtn").live("click", function() {
		$("form").submit();
	});
});